#include <iostream>
#include <fstream>
#include <string>
#include <curl/curl.h>
#include <sstream>

const std::string VERSION = "1.0";  // 当前版本
const std::string VERSION_URL = "http://yourserver.com/version.txt";
const std::string UPDATE_FILE_URL = "https://files.cupb.top/api/file/download?fileUuid=88196ecfcfc3df353876a81e78452679";
const std::string UPDATE_FILE_PATH = "client_latest.pdf";

// 用于存储下载内容的回调函数
size_t WriteCallback(void* contents, size_t size, size_t nmemb, void* userp) {
    ((std::string*)userp)->append((char*)contents, size * nmemb);
    return size * nmemb;
}

// 下载文件函数
bool DownloadFile(const std::string& url, const std::string& outFile) {
    CURL* curl;
    FILE* fp;
    CURLcode res;
    curl = curl_easy_init();
    if (curl) {
        fp = fopen(outFile.c_str(), "wb");
        curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 3); //连接超时限制
        curl_easy_setopt(curl, CURLOPT_TIMEOUT, 20); //整个CURL操作的超时限制
        curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
//        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, NULL);
        curl_easy_setopt(curl, CURLOPT_READFUNCTION, &fread);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
        curl_easy_setopt(curl, CURLOPT_VERBOSE, 1); //显示CURL库详细的操作信息
        curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1L);
        try {
            res = curl_easy_perform(curl); // 发送数据
            curl_easy_cleanup(curl);
            fclose(fp);
            return (res == CURLE_OK);
        } catch (const std::exception& e) {
            std::cout << e.what() << std::endl;
        }

    }
    return false;
}

// 检查更新
bool CheckForUpdates() {
    CURL* curl;
    CURLcode res;
    std::string readBuffer;
    curl = curl_easy_init();
    if (curl) {
        curl_easy_setopt(curl, CURLOPT_URL, VERSION_URL.c_str());
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
        res = curl_easy_perform(curl);
        curl_easy_cleanup(curl);
        if (res != CURLE_OK) {
            return false;
        }
    }
    std::istringstream ss(readBuffer);
    std::string serverVersion, downloadUrl;
    std::getline(ss, serverVersion);
    std::getline(ss, downloadUrl);
    if (serverVersion > VERSION) {
        downloadUrl = UPDATE_FILE_URL;
        std::cout << "New version available: " << serverVersion << std::endl;
        std::cout << "Downloading update..." << std::endl;
        return DownloadFile(downloadUrl, UPDATE_FILE_PATH);
    }
    return false;
}

int main1() {
    if (CheckForUpdates()) {
        std::cout << "Update downloaded. Please restart the application." << std::endl;
        // 可以在这里添加自动替换旧版本的逻辑，或提示用户手动重启
        // 比如使用以下代码重新启动新版本：
        // system(UPDATE_FILE_PATH.c_str());
    } else {
        std::cout << "You are using the latest version." << std::endl;
    }
    // 继续你的应用程序的其他逻辑
    return 0;
}
